/*
 * COPYRIGHT ©2016 AsiaInfo Big Data X. All RIGHT RESERVED.
 *
 * No part of this source code may be copied, used, or modified
 * without the express written consent of AsiaInfo BDX.
 */

package com.ai.notices.web.system.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XssUtil {

    private static Pattern pattern = Pattern.compile("(onabort|onblur|onchange|onclick|ondblclick|onerror|onfocus|onkeydown|onkeypress|onkeyup|onload|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onreset|onresize|onselect|onsubmit|onunload)[\\s]*(?==)",Pattern.CASE_INSENSITIVE);

    private XssUtil() {
    }

    /**
     * html编码处理掉&<>特殊字符
     **/
    private static String htmlEncode(char c) {
        switch (c) {
            case '&':
                return "&amp;";
            case '<':
                return "&lt;";
            case '>':
                return "&gt;";
	        case '"':
	           return"&quot;";
            default:
                return c + "";
        }
    }

    /**
     * 对传入的字符串str进行Html encode转换
     */
    public static String htmlEncode(String str) {
        if (str == null || str.trim().equals("")) return str;
        StringBuilder encodeStrBuilder = new StringBuilder();
        for (int i = 0, len = str.length(); i < len; i++) {
            encodeStrBuilder.append(htmlEncode(str.charAt(i)));
        }
        return encodeStrBuilder.toString();
    }

    /**
     * 对传入的字符串数组进行Html encode转换，返回String数组
     */
    public static String[] htmlEncode(String[] strs) {
        if (strs == null || strs.length < 1) return strs;
        String[] encodeStrs = new String[strs.length];
        for (int i = 0; i < strs.length; i++) {
            String str = strs[i];
            StringBuilder encodeStrBuilder = new StringBuilder();
            for (int j = 0, len = str.length(); j < len; j++) {
                encodeStrBuilder.append(htmlEncode(str.charAt(j)));
            }
            encodeStrs[i] = encodeStrBuilder.toString();
        }
        return encodeStrs;
    }

    /**
     * 检验URL Param，如果存在非法参数，去除该敏感信息，避免xss攻击.
     * 如果存在JavaScript敏感词，返回空字符串，如果不存在返回Html编码后的字符串
     */
    public static String checkParam(String str) {
        String resultStr = "";
        if (str == null || str.isEmpty()) return resultStr;
        /* 正则表达式匹配JavaScript事件，进行过滤 */
        Matcher matcher = pattern.matcher(str);
        boolean rsFind = matcher.find();
        if (!rsFind) {
            resultStr = str;
        } else {
            resultStr = matcher.replaceAll("");
        }
        return resultStr;
    }
}
